package com.fulihui.information.core.oss;


import lombok.extern.slf4j.Slf4j;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;

/**
 * Created by LeeSon on 2016/12/26 0026.
 */
@Slf4j
public class ImgKit {
    /**
     * 下载图片
     *
     * @param imgUrl
     * @param savePath
     * @param filename
     * @return 绝对路径
     */
    public static String downloadImg(String imgUrl, String savePath, String filename) {
        try {
            URL url = new URL(imgUrl);
            URLConnection urlConnection = url.openConnection();
            urlConnection.setReadTimeout(3 * 1000);
            // 输入流
            InputStream is = urlConnection.getInputStream();
            // 1K的数据缓冲
            byte[] bs = new byte[1024];
            // 读取到的数据长度
            int len;
            // 输出的文件流
            File sf = new File(savePath);
            if (!sf.exists()) {
                sf.mkdirs();
            }
            OutputStream os = new FileOutputStream(sf.getPath() + File.separator + filename);
            // 开始读取
            while ((len = is.read(bs)) != -1) {
                os.write(bs, 0, len);
            }
            // 完毕，关闭所有链接
            os.close();
            is.close();

            return sf.getAbsolutePath() + File.separator + filename;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }

        return null;
    }

    /**
     * 截取GIF第一张图片
     *
     * @param filePath
     * @param tag      用于区别于原图名称
     * @return
     */
    public static boolean gifFirst(String filePath, String tag) {
        try {
            //要操作的图片
            FileInputStream is = new FileInputStream(filePath);
            //把图片读取读取到内存的流
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            byte buffer[] = new byte[1024];
            int leng = 0;
            while ((leng = is.read(buffer)) != -1) {
                bos.write(buffer, 0, leng);
            }
            //截取第一张图
            BufferedImage bimage = ImageIO
                    .read(new ByteArrayInputStream(bos.toByteArray(), 0, bos.size()));
            ImageIO.write(bimage, "png", new File(filePath + tag));
            is.close();
            bos.close();
            return true;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return false;
    }

    /**
     * byte数组转换成16进制字符串
     *
     * @param src
     * @return
     */
    private static String bytesToHexString(byte[] src) {
        StringBuilder stringBuilder = new StringBuilder();
        if (src == null || src.length <= 0) {
            return null;
        }

        for (int i = 0; i < src.length; i++) {
            int v = src[i] & 0xFF;
            String hv = Integer.toHexString(v);
            if (hv.length() < 2) {
                stringBuilder.append(0);
            }
            stringBuilder.append(hv);
        }
        return stringBuilder.toString();
    }

    /**
     * 根据文件流读取图片文件真实类型
     *
     * @param is
     * @return
     */
    public static EImgFileHeaderType getTypeByStream(InputStream is) {
        byte[] b = new byte[4];
        try {
            is.read(b, 0, b.length);
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        } finally {
            try {
                is.reset();
            } catch (IOException e) {
                log.error(e.getMessage(), e);
            }
        }

        String type = bytesToHexString(b).toUpperCase();
        if (type.contains(EImgFileHeaderType.JPEG.getCode())) {
            return EImgFileHeaderType.JPEG;
        } else if (type.contains(EImgFileHeaderType.PNG.getCode())) {
            return EImgFileHeaderType.PNG;
        } else if (type.contains(EImgFileHeaderType.GIF.getCode())) {
            return EImgFileHeaderType.GIF;
        }

        return null;
    }
}